package book.config;

import book.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一结果返回:创建ResponseAdvice类,统一返回Result类对象
 *  实现 ResponseBodyAdvice接口,并在类上添加 @ControllerAdvice注解
 */
@Slf4j
@ControllerAdvice  //ControllerAdvice : 控制器通知类
public class ResponseAdvice implements ResponseBodyAdvice {
    private final ObjectMapper jacksonObjectMapper;

    public ResponseAdvice(ObjectMapper jacksonObjectMapper) {
        this.jacksonObjectMapper = jacksonObjectMapper;
    }

    /**
     *该方法用于判断 beforeBodyWrite方法是否执行
     * @return  true:执行,false:不执行
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
//      当返回的结果已经是Result时,直接返回Result就行,不用再进行二次封装了
       if(body instanceof Result){
           return body;
       } else if(body instanceof String){
           //当返回的结果为字符传时,需要特殊处理，
           // 使⽤SpringBoot内置提供的Jackson来实现信息的序列化
           return jacksonObjectMapper.writeValueAsString(Result.success(body));
       }
        Result result=Result.success(body);
        log.info("统一结果处理,返回Result: {}" ,body);
        return result;
    }
}
